package yxy.banana.socket.controlled;

import java.util.HashMap;

import yxy.apple.util.Sequencer;

public class ChannelManager<H extends ControlledHandler> {
	private Sequencer sequencer = new Sequencer(1, 0x0000FFFF);

	private HashMap<Integer, H> mapping = new HashMap<>();

	/**
	 * 添加入map并返回新分配的channel值
	 * 
	 * @param handler
	 * @return
	 */
	public synchronized int add(H handler) {
		int next = this.sequencer.next();
		while (this.mapping.containsKey(next)) {
			next = this.sequencer.next();
		}
		this.mapping.put(next, handler);
		return next;
	}

	public synchronized H remove(int channel) {
		return this.mapping.remove(channel);
	}

	public synchronized H find(int channel) {
		return this.mapping.get(channel);
	}

	public int mapped() {
		return this.mapping.size();
	}
}
